<?php
namespace Admin\Model;
use Think\Model;

class CategoryModel extends Model 
{
	protected $insertFields = array('cat_name','parent_id','is_floor');
	protected $updateFields = array('id','cat_name','parent_id','is_floor');
	protected $_validate = array(
		array('cat_name', 'require', '分类名称不能为空！', 1, 'regex', 3),
		array('cat_name', '1,30', '分类名称的值最长不能超过 30 个字符！', 1, 'length', 3),
		array('parent_id', 'number', '上级分类id,0:顶级分类必须是一个整数！', 2, 'regex', 3),
	);
	public function search($pageSize = 20)
	{
		/**************************************** 搜索 ****************************************/
		$where = array();
		if($cat_name = I('get.cat_name'))
			$where['cat_name'] = array('like', "%$cat_name%");
		if($parent_id = I('get.parent_id'))
			$where['parent_id'] = array('eq', $parent_id);
		/************************************* 翻页 ****************************************/
		$count = $this->alias('a')->where($where)->count();
		$page = new \Think\Page($count, $pageSize);
		// 配置翻页的样式
		$page->setConfig('prev', '上一页');
		$page->setConfig('next', '下一页');
		$data['page'] = $page->show();
		/************************************** 取数据 ******************************************/
		$data['data'] = $this->alias('a')->where($where)->group('a.id')->limit($page->firstRow.','.$page->listRows)->select();
		return $data;
	}
	// 添加前
	protected function _before_insert(&$data, $option)
	{
	}
	// 修改前
	protected function _before_update(&$data, $option)
	{
	}
	// 删除前
	protected function _before_delete($option)
	{
	    $children = $this->getChildren($option['where']['id']);
        if($children){
            $children = implode(',',$children);
            $model = new \Think\Model();
            $model->table('__CATEGORY__')->delete($children);
        }
	}

    /**获取导航条上的数据**/
    public function getNavData(){
        $catData = S('catData');
        if(!$catData){
            $all = $this->select();
            $ret = array();
            foreach($all as $k=>$v){
                if($v['parent_id'] == 0){
                    foreach ($all as $k1=>$v1){
                        if($v1['parent_id'] == $v['id']){
                            foreach ($all as $k2=>$v2){
                                if($v2['parent_id'] == $v1['id']){
                                    $v1['children'][] = $v2;
                                }
                            }
                            $v['children'][] = $v1;
                        }
                    }
                    $ret[] = $v;
                }
            }
            $ret = array_slice($ret,0,13);
            S('catData',$ret,0);
            return $ret;
        } else {
            return $catData;
        }
    }

    /**获取前台首页楼层中的数据**/
    public function floorData(){
        $floorData = S('floorData');
        if($floorData){
            return $floorData;
        } else {
            $ret = $this->where(array(
                'parent_id' => array('eq',0),
                'is_floor' => array('eq','是'),
            ))->select();
            $goodsModel = D('Admin/Goods');
            foreach ($ret as $k=>$v){
                $goodsId = $goodsModel->getGoodsIdByCatId($v['id']);
                !$goodsId && $goodsId = array(0);
                $ret[$k]['brand'] = $goodsModel->alias('a')
                    ->join('LEFT JOIN __BRAND__ b ON a.brand_id=b.id')
                    ->field('DISTINCT a.brand_id,b.brand_name,b.logo')
                    ->where(array(
                        'a.id' => array('in',$goodsId),
                        'a.brand_id' => array('neq',0),
                    ))->limit(9)->select();
                $ret[$k]['subCat'] = $this->where(array(
                    'parent_id' => array('eq',$v['id']),
                    'is_floor' => array('eq','否'),
                ))->select();
                $ret[$k]['recSubCat'] = $this->where(array(
                    'parent_id' => array('eq',$v['id']),
                    'is_floor' => array('eq','是'),
                ))->select();

               foreach ($ret[$k]['recSubCat'] as $k1=>&$v1){
                    $gids = $goodsModel->getGoodsIdByCatId($v1['id']);
                    !$gids && $gids = array(0);
                    $v1['goods'] = $goodsModel->field('id,mid_logo,goods_name,shop_price')->where(array(
                        'is_onsale' => array('eq',1),
                        'is_floor' => array('eq','是'),
                        'id' => array('in',$gids),
                    ))->order('sort_num ASC')->limit(8)->select();
                   //$ret[$k]['recSubCat'][$k1]['goods'] = $v1['goods'];

                }
            }

            //S('floorData',$ret,86400);
            return $ret;
        }
    }

    /**取出一个分类的所有上级分类**/
    public function parentPath($catId){
        static $ret = array();
        $info = $this->field('id,cat_name,parent_id')->find($catId);
        $ret[] = $info;
        if($info['parent_id'] > 0){
            $this->parentPath($info['parent_id']);
        }
        return $ret;
    }

    public function getChildren($catId){
        $data = $this->select();
        return $this->_getChildren($data,$catId,true);
    }

    private function _getChildren($data,$catId,$isClear = false){
        static $_ret = array();
        if($isClear){
            $_ret = array();
        }
        foreach ($data as $k=>$v){
            if($v['parent_id'] == $catId){
                $_ret[] = $v['id'];
                $this->_getChildren($data,$v['id']);
            }
        }
        return $_ret;
    }

    public function getTree(){
        $data = $this->select();
        return $this->_getTree($data);
    }

    private function _getTree($data,$parent_id=0,$level=0){
        static $_ret = array();
        foreach ($data as $k=>$v){
            if($v['parent_id'] == $parent_id){
                $v['level'] = $level;
                $_ret[] = $v;
                $this->_getTree($data,$v['id'],$level+1);
            }
        }
        return $_ret;
    }

    /****根据当前搜索出来的商品计算筛选条件****/
    public function getSearchConditionByGoodsId($goodsId){
        $ret = array(); //返回的数组
        $goodsModel = D('Admin/Goods');
        //$goodsId = $goodsModel->getGoodsIdByCatId($catId);
        !$goodsId && $goodsId = array(0);
        /*************品牌**************/
        //根据ID取出品牌ID再连品牌表取出品牌名称
        $ret['brand'] = $goodsModel->alias('a')
            ->field('DISTINCT brand_id,b.brand_name,b.logo')
            ->join('LEFT JOIN __BRAND__ b ON a.brand_id=b.id')
            ->where(array(
                'a.id' => array('in',$goodsId),
                'a.brand_id' => array('neq',0),
            ))->select();

        /*************价格区间段**************/
        $sectionCount = 6; //默认分几段
        //取出这个分类下最大和最小的价格
        $priceInfo = $goodsModel->field('MAX(shop_price) max_price,MIN(shop_price) min_price')
            ->where(array(
                'id' => array('in',$goodsId),
            ))->find();

        //最大价格和最小价格的区间
        $priceSection = $priceInfo['max_price'] - $priceInfo['min_price'];

        //分类下商品的数量
        $goodsCount = count($goodsId);
        //只有商品数量有这些时价格才分段
        if($goodsCount > 1){
            if($priceSection < 100){
                $sectionCount = 2;
            } elseif($priceSection < 1000) {
                $sectionCount = 4;
            } elseif($priceSection < 10000) {
                $sectionCount = 6;
            } else {
                $sectionCount = 7;
            }
            //根据这些段数分段
            $pricePerSection = ceil($priceSection / $sectionCount); //每段的范围
            $price = array(); //存放最终的分段数据
            $firstPrice = 0; //第一个价格段的开始价格
            //循环每个段
            for($i=0;$i<$sectionCount;$i++){
                //每段结束的价格
                $_tmpEnd = $firstPrice + $pricePerSection;
                //把结束的价格取整
                $_tmpEnd = ((ceil($_tmpEnd /100))*100-1);
                $price[] = $firstPrice . '-' . $_tmpEnd;
                //计算下一个价格段的开始价格
                $firstPrice = $_tmpEnd+1;
        }
            //放到返回的数组中
            $ret['price'] = $price;
        }
        /*************商品属性**************/
        $gaModel = D('GoodsAttr');
        $gaData = $gaModel->alias('a')
            ->field('DISTINCT a.attr_id,a.attr_value,b.attr_name')
            ->join('LEFT JOIN __ATTRIBUTE__ b ON a.attr_id=b.id')
            ->where(array(
                'a.goods_id' => array('in',$goodsId),
                'a.attr_value' => array('neq',''),
            ))->select();
        //处理这个属性数组：把属性相同的放到一起用属性名称作为下标->二维转三维
        $_gaData = array();
        foreach($gaData as $k => $v){
            $_gaData[$v['attr_name']][] = $v;
        }
        //放到返回数组中
        $ret['gaData'] = $_gaData;
        //返回数组
        return $ret;
    }
}